package com.hdoit.ares.logical.brokerage.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.hdoit.ares.logical.acc.dao.IAccountInfoDao;
import com.hdoit.ares.logical.acc.dao.IGoldenBeanDetailDao;
import com.hdoit.ares.logical.acc.dao.IGoldenBeanInfoDao;
import com.hdoit.ares.logical.acc.dao.IIncomeDetailDao;
import com.hdoit.ares.logical.acc.dao.IIncomeInfoDao;
import com.hdoit.ares.logical.acc.model.AccountInfo;
import com.hdoit.ares.logical.acc.model.GoldenBeanDetail;
import com.hdoit.ares.logical.acc.model.GoldenBeanInfo;
import com.hdoit.ares.logical.acc.model.IncomeDetail;
import com.hdoit.ares.logical.acc.model.IncomeInfo;
import com.hdoit.ares.logical.brokerage.dao.IShareBrokerageDao;
import com.hdoit.ares.logical.brokerage.model.ShareBrokerage;
import com.hdoit.ares.logical.brokerage.service.IShareBrokerageService;
import com.hdoit.ares.logical.viewmodel.brokerage.ShareBrokerageSearch;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.selfcommon.enums.acc.GoldenBeanType;
import com.hdoit.ares.selfcommon.enums.acc.HesitatePeriodState;
import com.hdoit.ares.selfcommon.enums.acc.IncomeState;
import com.hdoit.ares.selfcommon.enums.acc.State;
import com.hdoit.ares.selfcommon.enums.brokerage.ConfirmState;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.setting.dao.IParamOptionDao;
import com.tennetcn.common.logical.setting.model.ParamOption;
import com.tennetcn.common.message.DaoBaseException;
import com.tennetcn.common.message.LoginModel;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.RandomUtils;
/**
 * @author      yujinhui
 * @email       
 * @createtime  2017年12月01日 15:27:09
 * @comment
 */
@Component
public class ShareBrokerageServiceImpl extends SuperService<ShareBrokerage> implements IShareBrokerageService{
	public final static String StrOrderNum = "yyyyMMddHHmmss";
	private  IShareBrokerageDao shareBrokerageDao;
    
	public IShareBrokerageDao getShareBrokerageDao() {
		return shareBrokerageDao;
	}
    
	@Resource
	public void setShareBrokerageDao(IShareBrokerageDao shareBrokerageDao) {
		this.shareBrokerageDao = shareBrokerageDao;
	}
    
	private IParamOptionDao paramOptionDao;

	public IParamOptionDao getParamOptionDao() {
		return paramOptionDao;
	}
	@Resource
	public void setParamOptionDao(IParamOptionDao paramOptionDao) {
		this.paramOptionDao = paramOptionDao;
	}

	private IAccountInfoDao accountInfoDao;

	public IAccountInfoDao getAccountInfoDao() {
		return accountInfoDao;
	}
	@Resource
	public void setAccountInfoDao(IAccountInfoDao accountInfoDao) {
		this.accountInfoDao = accountInfoDao;
	}
	
	private IGoldenBeanInfoDao goldenBeanInfoDao;
	public IGoldenBeanInfoDao getGoldenBeanInfoDao() {
		return goldenBeanInfoDao;
	}
	@Resource
	public void setGoldenBeanInfoDao(IGoldenBeanInfoDao goldenBeanInfoDao) {
		this.goldenBeanInfoDao = goldenBeanInfoDao;
	}
	
	private IGoldenBeanDetailDao goldenBeanDetailDao;
	public IGoldenBeanDetailDao getGoldenBeanDetailDao() {
		return goldenBeanDetailDao;
	}
	@Resource
	public void setGoldenBeanDetailDao(IGoldenBeanDetailDao goldenBeanDetailDao) {
		this.goldenBeanDetailDao = goldenBeanDetailDao;
	}
	
	private IIncomeInfoDao incomeInfoDao;
	public IIncomeInfoDao getIncomeInfoDao() {
		return incomeInfoDao;
	}
    @Resource
	public void setIncomeInfoDao(IIncomeInfoDao incomeInfoDao) {
		this.incomeInfoDao = incomeInfoDao;
	}
    
    private IIncomeDetailDao incomeDetailDao;
	public IIncomeDetailDao getIncomeDetailDao() {
		return incomeDetailDao;
	}
    @Resource
	public void setIncomeDetailDao(IIncomeDetailDao incomeDetailDao) {
		this.incomeDetailDao = incomeDetailDao;
	}

	@Override
	public List<ShareBrokerage> queryList(ShareBrokerageSearch search, PagerModel pagerModel) {
		return shareBrokerageDao.queryList(search, pagerModel);
	}

	@Override
	public List<ShareBrokerage> queryList(ShareBrokerageSearch search) {
		return shareBrokerageDao.queryList(search);
	}

	@Override
	public int queryCount(ShareBrokerageSearch search) {
		return shareBrokerageDao.queryCount(search);
	}

	@Override
	public int queryMaxGroupNum() {
		return shareBrokerageDao.queryMaxGroupNum();
	}

	@Override
	public boolean insertAccountInfo(String brokerageId,LoginModel loginModel) {
		List<ShareBrokerage> ShareBrokerages =  new ArrayList<ShareBrokerage>();
		ShareBrokerages = shareBrokerageDao.queryListByBrokerageId(brokerageId);
		
		//避免并发操作
	    if(ConfirmState.confirmed.equals(ShareBrokerages.get(0).getConfirmState())){
			 return false;
		}
		
		List<AccountInfo> accountInfos = new ArrayList<AccountInfo>();
		List<GoldenBeanDetail> goldenBeanDetails = new ArrayList<GoldenBeanDetail>();
		List<GoldenBeanInfo> goldenBeanInfos = new ArrayList<GoldenBeanInfo>();
		List<IncomeInfo> incomeInfos = new ArrayList<IncomeInfo>();
		List<IncomeDetail> incomeDetails = new ArrayList<IncomeDetail>();
		
		for(ShareBrokerage shareBrokerage:ShareBrokerages){
			//在账户表中插入数据，即将奖金打入相应账户
			AccountInfo accountInfo = new AccountInfo();
			accountInfo = accountInfoDao.queryModelByCustomerId(shareBrokerage.getCustomerId());
			accountInfo.setModelStatus(ModelStatus.update);
			
			double money = shareBrokerage.getMoney();
						
			double toGoldBean = new BigDecimal(String.valueOf(shareBrokerage.getPromote())).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			
			
			
			double toSec =  new BigDecimal(String.valueOf(shareBrokerage.getSecondShare())).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			double toFir =  new BigDecimal(String.valueOf(shareBrokerage.getFirstShare())).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			double toSer =  new BigDecimal(String.valueOf(shareBrokerage.getServer())).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			double toHat =  new BigDecimal(String.valueOf(shareBrokerage.getHatch())).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			
			
			double toMoney = (toSec + toFir + toSer + toHat);
			
			ParamOption paramOption = paramOptionDao.queryModelByParamName("exchange");
			int exchangeRate = Integer.valueOf(paramOption.getParamValue());
			double goldenBean = exchangeRate * toGoldBean;
			
			accountInfo.setGoldenBean(accountInfo.getGoldenBean() + goldenBean);
			accountInfos.add(accountInfo);
			
			
			//将分润追踪表中的状态改为确认
			shareBrokerage.setConfirmState(ConfirmState.confirmed);
			shareBrokerage.setModifyDate(DateUtils.getCurrent());
			if(loginModel != null){
				shareBrokerage.setModifyUserId(loginModel.getLoginId());
				shareBrokerage.setModifyUserName(loginModel.getLoginName());
			}
			shareBrokerage.setModelStatus(ModelStatus.update);
			
			//产生金豆账户记录
			GoldenBeanInfo goldenBeanInfo = goldenBeanInfoDao.queryModelByCustomerId(shareBrokerage.getCustomerId());
			
			goldenBeanInfo.setPromotionAward(money * exchangeRate * shareBrokerage.getPromote());
			goldenBeanInfo.setModelStatus(ModelStatus.update);
			goldenBeanInfos.add(goldenBeanInfo);
			
			//产生金豆明细记录,奖励来源主要是推广奖
			if(goldenBean > 0.0){
				GoldenBeanDetail goldenBeanDetail = new GoldenBeanDetail();
				goldenBeanDetail.setId(CommonUtils.getKeyId());
				goldenBeanDetail.setGoldenBeanAccount(goldenBean);
				goldenBeanDetail.setState(State.income);
				goldenBeanDetail.setGoldenBeanType(GoldenBeanType.promotionAward);
				goldenBeanDetail.setTime(shareBrokerage.getGenerateDate());
				goldenBeanDetail.setCustomerId(shareBrokerage.getCustomerId());
				goldenBeanDetail.setGoldenBeanBalance(accountInfo.getGoldenBean());
				goldenBeanDetail.setAccountNo(accountInfo.getAccountNo());
				goldenBeanDetail.setModelStatus(ModelStatus.add);
				goldenBeanDetail.setHesitatePeriod(shareBrokerage.getHesitateDay());
				goldenBeanDetail.setHesitatePeriodState(HesitatePeriodState.Hesitating);
				goldenBeanDetail.setPercent(shareBrokerage.getPromote());
				goldenBeanDetail.setPurchaser(ShareBrokerages.get(0).getCustomerName());
				goldenBeanDetail.setPurchasedProduct(shareBrokerage.getProductName());
				goldenBeanDetail.setOutTradeNo("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
				goldenBeanDetail.setCommercialInsurance(money);
				goldenBeanDetails.add(goldenBeanDetail);
			}
			
			//其它奖励直接转入奖金表中
			IncomeInfo incomeInfo = incomeInfoDao.queryIncomeInfo(shareBrokerage.getCustomerId());
			incomeInfo.setIncomeBalance(incomeInfo.getIncomeBalance() + toMoney);
			
			System.err.println("toMoney的钱\t" + toMoney);
			//一级分享奖
			if(shareBrokerage.getFirstShare() > 0.00){
				
				incomeInfo.setFirstSharingAward(toFir);
				IncomeDetail incomeDetail = incomeDetailHelp(money,accountInfo,shareBrokerage,ShareBrokerages.get(0),shareBrokerage.getFirstShare(),IncomeState.firstSharingAward);
				incomeDetails.add(incomeDetail);
			}
			//二级分享奖
            if(shareBrokerage.getSecondShare() > 0.00){
            	incomeInfo.setSecondSharingAward(toSec);
            	IncomeDetail incomeDetail = incomeDetailHelp(money,accountInfo,shareBrokerage,ShareBrokerages.get(0),shareBrokerage.getSecondShare(),IncomeState.secondSharingAward);
				incomeDetails.add(incomeDetail);
            }
            //服务奖
            if(shareBrokerage.getServer() > 0.00){
				incomeInfo.setServiceAward(toSer);
				IncomeDetail incomeDetail = incomeDetailHelp(money,accountInfo,shareBrokerage,ShareBrokerages.get(0),shareBrokerage.getServer(),IncomeState.serviceAward);
				incomeDetails.add(incomeDetail);
            }
            //孵化奖
            if(shareBrokerage.getHatch() > 0.00){
				incomeInfo.setHatcheryAward(toHat);
				IncomeDetail incomeDetail = incomeDetailHelp(money,accountInfo,shareBrokerage,ShareBrokerages.get(0),shareBrokerage.getHatch(),IncomeState.hatcheryAward);
				incomeDetails.add(incomeDetail);
            }
            incomeInfo.setModelStatus(ModelStatus.update);
            incomeInfos.add(incomeInfo);	
	
		}
		
		try {
			//变为确认之后才打入账户，主要考虑到可能钱打到账户状态还没改变，造成重复误操作
			if(shareBrokerageDao.applyChanges(ShareBrokerages)){
				
				if(accountInfoDao.applyChanges(accountInfos)){
					if(goldenBeanDetails.size() > 0 && goldenBeanDetails != null && incomeDetails.size() > 0 && incomeDetails != null){
						return (goldenBeanInfoDao.applyChanges(goldenBeanInfos) && goldenBeanDetailDao.applyChanges(goldenBeanDetails) && incomeInfoDao.applyChanges(incomeInfos) && incomeDetailDao.applyChanges(incomeDetails));
					}else if(goldenBeanDetails.size() > 0 && goldenBeanDetails != null){
						return (goldenBeanInfoDao.applyChanges(goldenBeanInfos) && goldenBeanDetailDao.applyChanges(goldenBeanDetails) && incomeInfoDao.applyChanges(incomeInfos));
					}else if(incomeDetails.size() > 0 && incomeDetails != null){
						return (goldenBeanInfoDao.applyChanges(goldenBeanInfos)  && incomeInfoDao.applyChanges(incomeInfos) && incomeDetailDao.applyChanges(incomeDetails));
					}
					
					return (goldenBeanInfoDao.applyChanges(goldenBeanInfos) && incomeInfoDao.applyChanges(incomeInfos));
				};
			}
		} catch (DaoBaseException e) {
			e.printStackTrace();
		}
		
		return false;
	}

	//提取公共代码
	public IncomeDetail incomeDetailHelp(double money,AccountInfo accountInfo,ShareBrokerage shareBrokerage,ShareBrokerage buyer,double percent,String incomeState){
		IncomeDetail incomeDetail = new IncomeDetail();
		incomeDetail.setId(CommonUtils.getKeyId());
		incomeDetail.setAccountNo(accountInfo.getAccountNo());
		incomeDetail.setIncomeState(incomeState);
		incomeDetail.setTime(shareBrokerage.getGenerateDate());
		incomeDetail.setState(State.income);
		
		incomeDetail.setIncomeAccount(new BigDecimal(String.valueOf(percent)).multiply(new BigDecimal(String.valueOf(money))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
		
		incomeDetail.setPercent(percent);
		incomeDetail.setIncomeBalance(accountInfo.getBalance());
		incomeDetail.setPurchaser(buyer.getCustomerName());
		incomeDetail.setPurchasedProduct(shareBrokerage.getProductName());
		incomeDetail.setCommercialInsurance(money);
		incomeDetail.setOutTradeNo("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
		incomeDetail.setCustomerId(shareBrokerage.getCustomerId());
		incomeDetail.setHesitatePeriod(shareBrokerage.getHesitateDay());
		incomeDetail.setHesitatePeriodState(HesitatePeriodState.Hesitating);
		incomeDetail.setModelStatus(ModelStatus.add);

		
		return incomeDetail;
	}

	@Override
	public HashMap<String, String> queryShareBrokerageForStatistic(CustomerSearch search) {
		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<ShareBrokerage> shareBrokerages = shareBrokerageDao.queryShareBrokerageForStatistic(search);
	    
		
			for(ShareBrokerage shareBrokerage:shareBrokerages){
				now.setTime(shareBrokerage.getGenerateDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				int value = Integer.valueOf(map.get(key)) + 1;
				map.replace(key, String.valueOf(value));
			}
		
		return map;
	}

	@Override
	public HashMap<String, String> queryShareBrokerageForMoney(CustomerSearch search) {
		HashMap<String,String> map = new HashMap<String,String>();
		
		Calendar now = Calendar.getInstance();
		//获取当前时间
		now.setTime(DateUtils.getCurrent());
		//获取当前月份的天数
		int days = now.getActualMaximum(Calendar.DATE);
		
		for(int i = 1; i <= days; i++){
			map.put(String.valueOf(i),String.valueOf(0));
		}
		
		List<ShareBrokerage> shareBrokerages = shareBrokerageDao.queryShareBrokerageForStatistic(search);
	    
		
			for(ShareBrokerage shareBrokerage:shareBrokerages){
				now.setTime(shareBrokerage.getGenerateDate());
				String key = "" + now.get(Calendar.DAY_OF_MONTH);
				double value = Double.valueOf(map.get(key)) + shareBrokerage.getMoney();
				map.replace(key, String.valueOf(value));
			}
		
		return map;
	}
	
}
